<template>
  <div class="app-page">
    <!-- 新增和编辑退残单 -->
    <el-dialog
      v-el-drag-dialog
      :title="type === 'add' ? '新增退残单': (type ==='audit'?'退残单--'+originalBillCode : '编辑退残单')"
      :visible.sync="visible"
      width="1200px"
      @closed="reset"
    >
      <div class="center">
        <!-- 描述列表 -->
        <el-form ref="dataForm" class="form" :model="temp" :rules="rules" label-position="right" label-width="100px">
          <el-form-item label="退残机构:" prop="orgId">
            <el-tree-select
              v-model="temp.orgId"
              :clearable="true"
              :disabled="type==='edit' || type==='audit'"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props:{
                  value:'orgId',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData
              }"
              @select-clear="selectClear"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item label="退残人:" prop="targetUserId">
            <el-select v-model="temp.targetUserId" clearable :disabled="type==='audit'||type==='detail'" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
              <el-option
                v-for="item in ownersList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="退残时间:" prop="happendTime">
            <el-date-picker
              v-model="temp.happendTime"
              :picker-options="pickerOptions"
              type="datetime"
              unlink-panels
              placeholder="选择日期时间"
              :disabled="recycleDisable"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="支付方式:" prop="paymentMethod">
            <el-select v-model="temp.paymentMethod" placeholder="请选择" :disabled="type==='audit'||type==='detail'">
              <el-option
                v-for="item in paymentMethodList"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="type==='add'||type==='edit'" label="退残单号:" prop="billCode">
            <el-input v-model="temp.billCode" :disabled="type==='edit'" placeholder="手工输入或自动产生">
              <el-button v-if="type==='add'" slot="append" class="append-search" @click.prevent="getCode">获取</el-button>
            </el-input>
          </el-form-item>
          <el-form-item v-if="type==='add'||type==='edit'" label="客户编号:" prop="text" style="width: 92%;">
            <el-input v-model.trim="text" placeholder="请输入" @keyup.enter.native="e=>searchCsm(e)">
              <!-- <el-select slot="prepend" v-model="textType" style="width: 100px;" placeholder="请选择">
                <el-option label="客户编号" value="csmCode" />
              </el-select> -->
              <el-button slot="append" class="append-search" @click="e=>searchCsm(e)">查询</el-button>
            </el-input>
          </el-form-item>
          <el-form-item v-if="type==='add'||type==='edit'" label-width="0" style="width: 8%;">
            <div>
              &nbsp;&nbsp;
              <el-button slot="append" class="append-search" @click="replacement">重置</el-button>
            </div>
          </el-form-item>

          <el-form-item label="退残客户:" prop="csmName">
            <el-input v-model="temp.csmName" disabled />
          </el-form-item>
          <el-form-item label="电话:" prop="csmPhone">
            <el-select v-model="temp.csmPhone" :disabled="type==='audit'||type==='detail'" placeholder="请选择">
              <el-option
                v-for="item in csmPhoneList"
                :key="item.csmPhone"
                :label="item.csmPhone"
                :value="item.csmPhone"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地址:" prop="csmAddress">
            <el-select v-model="temp.csmAddress" :disabled="type==='audit'||type==='detail'" placeholder="请选择">
              <el-option
                v-for="item in csmAddressList"
                :key="item.csmAddress"
                :label="item.csmAddress"
                :value="item.csmAddress"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" prop="remark" class="block">
            <el-input v-model="temp.remark" :disabled="type==='audit'||type==='detail'" type="textarea" :rows="3" maxlength="255" show-word-limit />
          </el-form-item>
        </el-form>
        <editable-table v-if="type==='add'||type==='edit'" ref="editableTable" :temp="temp" />
        <no-editable-table v-if="type==='audit'||type==='detail'" ref="editableTable" :temp="temp" />
      </div>
      <div v-if="type==='add'||type==='edit'" slot="footer" class="dialog-footer">
        <el-button @click="reset">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
          保存
        </el-button>
      </div>
      <div v-if="type==='audit'" slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.submit" type="primary" @click="audit(1)">
          通过
        </el-button>
        <el-button :loading="$loadingPlugin.submit" type="danger" @click="audit(2)">
          驳回
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { queryOrgCode, queryCsmInfo, querySaveRecycleOrder, queryRecycleOrderDetailTc, queryPassAuditRecycleOrder, csDeliverUserList } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { defaultPaymentMethodMap } from '@/utils/map'
  import moment from 'dayjs'
  import EditableTable from './EditableTable2'
  import NoEditableTable from './NoEditableTable'

  export default {
    name: 'retiringOrder',
    components: {
      EditableTable, NoEditableTable
    },
    props: {
      paymentMethodMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          }
        },
        recycleDisable: true,
        paymentMethodList: [
          { value: 1, desc: '现金' },
          { value: 16, desc: '月结' },
          { value: 256, desc: '预付卡' }
          // { value: 2, desc: '微信' },
          // { value: 128, desc: '支付宝' }
        ],
        type: 'add',
        visible: false,
        originalBillCode: '',
        gdStatusMap: [],
        gdStatusMapOrigin: [],
        treeData: [],
        currentOrg: null,
        ownersList: [],
        csmInfo: null,
        csmPhoneList: [],
        csmAddressList: [],
        defaultPaymentMethodMap,
        textType: 'csmCode',
        text: '',
        temp: {
          orgId: '', // 所属机构orgId
          targetUserId: '',
          happendTime: moment().format('YYYY-MM-DD HH:mm'),
          paymentMethod: 1,
          billCode: '',
          csmName: '',
          csmPhone: '',
          csmAddress: '',
          remark: ''
        },
        rules: {
          csmName: [{ required: true, message: '请选择退残客户', trigger: 'change' }],
          orgId: [{ required: true, message: '请选择退残机构', trigger: 'change' }],
          targetUserId: [{ required: true, message: '请选择退残人', trigger: 'change' }],
          csmPhone: [{ required: false, message: '请选择电话', trigger: 'change' }],
          csmAddress: [{ required: false, message: '请选择地址', trigger: 'change' }]
        },
        goodsTypeListAll: [],
        goodsListAll: [],
        goodsListAllOrigin: []
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData()])
    },
    methods: {
      open(temp, type) {
        if (type) this.type = type
        if (temp) {
          this.getDeaultData(temp)
          this.getOwnersList(temp.orgId)
          this.$nextTick(() => {
            this.$refs.editableTable.getData()
          })
        }
        if (type === 'add') {
          this.temp.orgId = this.treeData[0].orgId
          this.getOwnersList(this.temp.orgId)
        }
        // 设置退残时间可编辑状态
        this.setRecycleTime()
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.originalBillCode = temp.billCode
          }
        })
      },
      async getDeaultData(temp) {
        const res = await queryRecycleOrderDetailTc({ billCode: temp.billCode })
        this.temp = res.data
        if (res.data.csmPhone) this.searchCsm(null, res.data.csmPhone)
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnersList(value.orgId)
        this.$set(this.temp, 'targetUserId', '')
      },
      // 查询退残人列表
      async getOwnersList(orgId) {
        const res = await csDeliverUserList({
          deliveryOrgId: orgId
        })
        this.ownersList = res.data
      },
      setRecycleTime() {
        if (this.corpSettingData.sp2 >> 16 & 0x01) {
          this.recycleDisable = false
        } else {
          this.recycleDisable = true
        }
      },
      // 清空退残机构
      selectClear() {
        this.$set(this.temp, 'targetUserId', '')
        this.ownersList = []
      },
      // 获取编码
      async getCode() {
        if (!this.temp.orgId) {
          this.$message.warning('请选择退残机构')
          return
        }
        const res = await queryOrgCode({
          codeType: 16
        })
        this.temp.billCode = 'HSD' + this.temp.orgId + moment().format('MMDD') + res.data
      },
      // 查询客户
      async searchCsm(e, csmPhone) {
        if (!this.text && !csmPhone) {
          this.$message.error('查询条件不允许为空')
          return
        }
        const params = {
          csmStatus: 9, // 查询状态不是已注销的客户
          pageIndex: 1,
          pageSize: 20
        }
        if (!csmPhone) params[this.textType] = this.text
        else params.csmRgPhone = csmPhone
        const res = await queryCsmInfo(params)
        if (!csmPhone) {
          this.$set(this.temp, 'csmName', '')
          this.$set(this.temp, 'csmPhone', '')
          this.$set(this.temp, 'csmAddress', '')
        }

        this.csmInfo = res.data
        console.log(res.data)
        if (res.data) {
          if (res.data.phoneItems) this.csmPhoneList = res.data.phoneItems.filter(item => item.cpStatus === 2)
          if (res.data.addressItems) this.csmAddressList = res.data.addressItems
          this.$set(this.temp, 'csmName', res.data.csmName)
          if (this.csmPhoneList && this.csmPhoneList.length === 1) {
            this.$set(this.temp, 'csmPhone', this.csmPhoneList[0].csmPhone)
          }
          if (this.csmAddressList && this.csmAddressList.length === 1) {
            this.$set(this.temp, 'csmAddress', this.csmAddressList[0].csmAddress)
          }
          this.paymentMethodList = [{ value: 1, desc: '现金' }]
          this.$set(this.temp, 'paymentMethod', 1)
          if (this.csmInfo && this.csmInfo.settlementType === 2) {
            this.paymentMethodList.push({ value: 16, desc: '月结' })
            this.$set(this.temp, 'paymentMethod', 16)
            if (this.csmInfo.cardNo !== '') {
              this.paymentMethodList.push({ value: 256, desc: '预付卡' })
            }
          } else {
            if (this.csmInfo.cardType !== 0) {
              this.paymentMethodList.push({ value: 256, desc: '预付卡' })
              this.$set(this.temp, 'paymentMethod', 256)
            }
          }
        }
      },
      // 重置
      replacement() {
        this.text = ''
        this.$set(this.temp, 'csmName', '')
        this.$set(this.temp, 'csmPhone', '')
        this.$set(this.temp, 'csmAddress', '')
        this.csmPhoneList = []
        this.csmAddressList = []
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const org = this.orgList.find(item => item.orgId === this.temp.orgId)
          const targetUser = this.ownersList.find(item => item.userId === this.temp.targetUserId)
          const rows = this.$refs.editableTable.recycleGoodsList
          if (!rows || rows.length === 0) {
            this.$message.error('请添加退残商品')
            return
          }
          for (let i = 0; i < rows.length; i++) {
            if (!rows[i].goodsName) {
              this.$message.error('请选择退残商品')
              return
            }
            if (rows[i].pricingMode === 1) {
              // if (!rows[i].goodsCount) {
              //   this.$message.error(`请填写${rows[i].gtName}-${rows[i].goodsName}的退残数量`)
              //   return
              // }
              // rows[i].netWeight = 0
            } else {
              if (!rows[i].netWeight) {
                this.$message.error(`请填写${rows[i].gtName}-${rows[i].goodsName}的退残重量`)
                return
              }
              rows[i].goodsCount = 0
            }
            if (!rows[i].amount) {
              rows[i].amount = 0
            }
          }
          const params = {
            billCode: this.temp.billCode,
            billType: 2,
            orgId: this.temp.orgId,
            orgName: org.orgName,
            orgSNNo: org.orgSNNo,
            csmId: this.csmInfo ? this.csmInfo.csmId : this.temp.csmId,
            csmName: this.csmInfo ? this.csmInfo.csmName : this.temp.csmName,
            csmCode: this.csmInfo ? this.csmInfo.csmCode : this.temp.csmCode,
            csmPhone: this.temp.csmPhone,
            csmAddress: this.temp.csmAddress,
            targetUserId: this.temp.targetUserId,
            targetUser: targetUser.userName,
            remark: this.temp.remark,
            happendTime: moment(this.temp.happendTime).format(),
            isSub: 0,
            paymentMethod: this.temp.paymentMethod,
            recycleGoodsList: this.$refs.editableTable.recycleGoodsList
            // substituteGoodsList: this.$refs.editableTable.substituteGoodsList
          }
          if (this.type === 'edit') params.originalBillCode = this.originalBillCode
          this.submit(params)
        })
      },
      async submit(params) {
        await querySaveRecycleOrder(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      },
      // 审核通过/驳回  isPass:1通过，2驳回
      async audit(isPass) {
        const params = {
          billCode: this.originalBillCode,
          isPass
        }
        isPass === 1 ? await queryPassAuditRecycleOrder(params) : await queryPassAuditRecycleOrder(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      },
      // 关闭
      reset() {
        this.type = 'add'
        this.text = ''
        this.temp = {
          orgId: '', // 所属机构orgId
          targetUserId: '',
          happendTime: moment().format('YYYY-MM-DD HH:mm'),
          paymentMethod: 1,
          billCode: '',
          csmName: '',
          csmPhone: '',
          csmAddress: '',
          remark: ''
        }
        this.csmInfo = null
        this.$nextTick(() => {
          this.visible = false
          this.$refs.dataForm.clearValidate()
          this.$refs.editableTable.reset()
        })
      }
    }
  }
</script>

<style lang='scss' scoped>
.app-page {
  /deep/ .cell .el-input-number--mini {
    width: 80px;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-between;
  & /deep/ .el-form-item {
    width: 33%;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
